#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include "Socket.hpp"
using namespace std;

std::string ip = "192.168.8.10";
std::uint16_t port = 8888;
int main()
{
    Sock sock("UDP");
    sock.Socket();
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    int i = 0;
    // 客户端不需要bind
    std::string msg = "abcdefghijklmnopqrstuvwxyz"; 
    int len = 0;
    srand(time(nullptr));
    while (true)
    {
        char buf[64] = {0};
        len = rand() % 16;
        i = rand() % 9;
        string sub = msg.substr(i,len);
        snprintf(buf, sizeof(buf), "%s,%d",sub.c_str(),i);
        int n = sendto(sock.Fd(), buf, sizeof(buf), 0, (struct sockaddr *)&server, sizeof(server));
        
        if (n > 0)
        {
            cout << "客户端# " << buf << endl;
        }
        else if(n == -1)
        {
            printf("%d-%s",errno,strerror(errno));
            cout << "-------------------------" << endl;
            exit(-1);
        }
        char ser_buf[128];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        n = recvfrom(sock.Fd(),ser_buf,sizeof(ser_buf),0,(struct sockaddr *)&peer,&len);
        if(n > 0)
        {
            ser_buf[n] = 0;
            cout << ser_buf << endl; 
            cout << "-------------------------" << endl;
        
        }
        sleep(1);

    }

    return 0;
}